﻿namespace dotnet_notes.Tools
{
    /// <summary>
    /// 随机工具类
    /// </summary>
    public static class RandomTool
    {
        // Random 不是线程安全的, 所以使用当前线程 id 作为种子值
        private static readonly Random random = new(Environment.CurrentManagedThreadId);

        private static readonly char[] chars =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();

        /// <summary>  
        /// 生成随机数字
        /// </summary>  
        /// <param name="digits">数字位数</param>  
        /// <returns></returns>  
        public static int GenerateNumber(int digits)
        {
            if (digits < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(digits), "数字位数必须大于 0");
            }

            // 计算数字范围
            int minValue = (int)Math.Pow(10, digits - 1);
            int maxValue = (int)Math.Pow(10, digits);

            lock (random) // 确保线程安全
            {
                return random.Next(minValue, maxValue); // 大于等于 minValue, 小于 maxValue
            }
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="length">字符串长度</param>
        /// <returns></returns>
        public static string GenerateString(int length)
        {
            if (length < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(length), "字符串长度必须大于 0");
            }

            var sb = new StringBuilder(length);

            lock (random) 
            {
                for (int i = 0; i < length; i++)
                {
                    char randomChar = chars[random.Next(chars.Length)];
                    sb.Append(randomChar);
                }
            }

            return sb.ToString();
        }
    }
}
